package com.trickytriads.services.remote
{
	import com.adobe.serialization.json.JSON;
	import com.trickytriads.events.GetPlayerDataEvent;
	import com.trickytriads.model.PlayerData;
	import com.trickytriads.services.FacebookService;
	import com.trickytriads.services.interfaces.I_PlayerService;
	
	import flash.events.EventDispatcher;
	
	import mx.controls.Alert;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.mxml.HTTPService;

	/**
	 * Implementation of player-related functions that use a remote PHP service.
	 */
	[Event(name="loadGeneric", type="com.trickytriads.events.LoadingEvent")]
	[Event(name="getPlayerDataDone", type="com.trickytriads.events.GetPlayerDataEvent")]	
	[ManagedEvents("getPlayerDataDone, loadGeneric")]		 
	public class PlayerServiceImpl_Remote extends EventDispatcher implements I_PlayerService
	{
		// Injected remote service
		[Inject]
		public var httpService:HTTPService;

		/**
		 * Gets the PlayerData object of the associated player.
		 */
		public function getPlayerById(pid:int):void
		{
			var sendObj:Object = FacebookService.makeFacebookObject();
			sendObj.GETPLAYERBYID = "true";
			sendObj.player_id = pid;
			httpService.addEventListener(ResultEvent.RESULT, getPlayerByIdResult);
			httpService.addEventListener(FaultEvent.FAULT, getPlayerByIdFault);
			httpService.send(sendObj);
		}
		
		/**
		 * Result handler for getPlayerById
		 */
		public function getPlayerByIdResult (evt:ResultEvent) : void
		{
			// Convert to generic Object class
			var resultObject:Object = JSON.decode(String(evt.result));
			if (resultObject.hasOwnProperty("I_AM_ERROR"))
			{
				// Alert an error message for now
				Alert.show("Error!!");				
			}
			else
			{
				// Make the playerdata from the received data
				var pdata:PlayerData = new PlayerData(resultObject.userid, resultObject.gold, resultObject.win, resultObject.loss, resultObject.experience, resultObject.isnew, "", "", resultObject.joindate);
				// Dispatch a done request
				dispatchEvent(new GetPlayerDataEvent(GetPlayerDataEvent.GETPLAYERDATA_DONE, -1, pdata));
			}
			// Remove event listeners
			httpService.removeEventListener(ResultEvent.RESULT, getPlayerByIdResult);
			httpService.removeEventListener(FaultEvent.FAULT, getPlayerByIdFault);
			
		}
		
		/**
		 * Fault handler for getPlayerById
		 */
		public function getPlayerByIdFault (evt:FaultEvent) : void
		{
			Alert.show("Fault in getPlayerById");
			httpService.removeEventListener(ResultEvent.RESULT, getPlayerByIdResult);
			httpService.removeEventListener(FaultEvent.FAULT, getPlayerByIdFault);
		}
	}
}